import json
import re
from django.contrib.auth import login
from django.http import JsonResponse
from django.conf import settings
from aijia_zufang.libs.qiniuyun.qiniu_storage import storage
from aijia_zufang.utils.iflogin import IfloginMixin
from django.contrib.auth import authenticate
from django.http import JsonResponse
from django.contrib.auth import logout
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from users.models import User


class UserInfoView(IfloginMixin, View):
    '''个人中心'''

    def get(self, request):
        '''展示个人信息'''

        # 获取用户图片
        avatar = request.user.avatar

        avatar_url = settings.MY_QINIUYUN_URL + avatar

        # 获取界面需要的数据,进行拼接
        user_info = {
            'avatar': avatar_url,
            'create_time': request.user.date_joined,
            'mobile': request.user.mobile,
            'name': request.user.username,
            'user_id': request.user.user_id

        }

        # 返回响应
        return JsonResponse({'errno': '0',
                             'errmsg': 'ok',
                             'info_data': user_info})

# 用户名修改
class UserPutView(IfloginMixin, View):
    def put(self, request):
        '''用户名修改'''

        # 接受参数
        dict = json.loads(request.body.decode())
        name = dict.get('name')

        try:
            request.user.username = name
            request.user.save()
        except Exception as e:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '数据错误'})

        return JsonResponse({'errno': 0,
                             'errmsg': '修改成功'})



class Upload_avatar(IfloginMixin,View): #上传头像类

    def post(self,request):
        image = request.FILES.get('avatar',None) #二进制
        if not image: #如果没有参数返回
            return JsonResponse({
                'errno':400,
                'errmsg':'缺少图片参数'
            })
        image_code = storage(image)     #获取图片在七牛云上的码
        if image_code is None:
            return JsonResponse( {
                'errno': 400,
                'errmsg': '上传失败'} )

        avatar_url = settings.MY_QINIUYUN_URL + image_code # 拼接url

        try: #修改用户表的avatar字段
            User.objects.filter(user = request.user).update(
                avatar = avatar_url)
        except Exception as e: #如果修改失败,返回
            return JsonResponse( {
                'errno': 400,
                'errmsg': '保存图片失败'} )

        return JsonResponse({
            'errno':'0',
            'errmsg':'头像上传成功',
            'data':{
                "avatar_url":avatar_url
            }
        })
# # 判断手机号是否重复注册
# class MobileCountView(View):
#
#     def get(self, request, mobile):
#
#         # 1.查询mobile在数据库中的个数
#         try:
#             count = User.objects.filter(mobile=mobile).count()
#         except Exception as e:
#             return JsonResponse({
#                 'errno':400,
#                 'errmsg':'访问数据库失败'
#             })
#
#         # 2.返回结果(json)
#         return JsonResponse({
#             'errno': 0,
#             'errmsg': 'ok',
#             'count':count
#         })




# 用户注册接口
class RegisterView(View):

    def post(self, request):
        '''接收参数，保存到数据库'''

        # 1.接收参数
        dict = json.loads(request.body)
        mobile = dict.get('mobile')
        phonecode_client = dict.get('phonecode')
        password = dict.get('password')
        password2 = dict.get('password2')


        # 2.校验(整体)
        if not all([mobile, phonecode_client, password]):
            return JsonResponse({'errno': 400,
                                 'errmsg': '缺少必传参数'})


        # 3.mobile检验
        if not re.match('^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 400,
                                 'errmsg': 'mobile格式有误'})

        # 4.password检验
        if not re.match('^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 400,
                                 'errmsg': 'password格式有误'})

        # password2 和 password
        # if password != password2:
        #     return JsonResponse({'errno': 400,
        #                          'errmsg': '两次密码输入不符'})


        # phonecode检验 (链接redis数据库, 获取链接对象)
        redis_conn = get_redis_connection('verify_code')

        # 从redis中取值
        phonecode_server = redis_conn.get('sms_%s' % mobile)

        # 判断该值是否存在
        if not phonecode_server:
            return JsonResponse({'errno': 400,
                                 'errmsg': '短信验证码过期'})

        # 把redis中取得值和前端发的值对比
        if phonecode_client != phonecode_server.decode():
            return JsonResponse({'errno': 400,
                                 'errmsg': '验证码有误'})

        # 保存到数据库 (username password mobile)
        try:
            user = User.objects.create_user(username=mobile, mobile = mobile,
                                            password=password)
        except Exception as e:

            return JsonResponse({'errno': 400,
                                 'errmsg': '保存到数据库出错'})

        # 实现状态保持
        login(request, user)


        # 拼接json返回
        return JsonResponse({'errno': 0,
                             'errmsg': 'ok'})

# 定义一个用户登录
class userLoginView(View):

    def post(self, request):
        '''登录接口'''

        # 接收参数
        dict = json.loads(request.body)
        username = dict.get('username')
        password = dict.get('password')

        # 校验参数
        if not all([username, password]):
            return JsonResponse({'errno':4004,
                                 'errmsg':'缺少必传参数'})

        # 验证是否能够登录
        user = authenticate(username=username,
                            password=password)

        # 判断是否为空,如果为空,返回
        if user is None:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '账号或密码错误'})

        return JsonResponse({'errno':0,
                             'errmsg':'登陆成功'})


    def get(self, request):
        '''判断用户是否登录'''

        if request.user.is_authenticated:
            ''''''

            return JsonResponse({'errno':'0',
                                 'errmsg':'已登录',
                                'data:{'
                                       'name':'mobile'
                                          '}'})
            #  如果登录,则正常返回该页面数据
        else:
            return JsonResponse({'errno':4004,
                                 'errmsg':'用户未登录'})


    def delete(self, request):
        '''实现退出登录逻辑'''

        # 清理session
        logout(request)

        # 创建response对象
        response = JsonResponse({'errno':0,
                                 'errmsg':'已退出'})

        # 调用对象的delete_cookie方法, 清除cookie
        response.delete_cookie('username')
        # 返回响应
        return response


